import React, { Fragment, useState, createRef } from 'react'
import { Button, Modal, Typography, message } from 'antd';
import ReactNbsp from 'react-nbsp'
import ImageUp, { UpFileResultInterface } from '../../../../../components/upImage/ecs'
import { post } from '../../../../../ajax/axios'
import { Api } from '../../../../../ajax/api'

const { Paragraph } = Typography;

const LocalImageRecognition = function () {

  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [imageUpRef] = useState(createRef<ImageUp>())
  const [wordsResult, setWordsResult] = useState<Array<any>>([])

  const okBtnClick = () => {
    if ( wordsResult.length > 0 ) {
      setWordsResult([])
      return
    }
    setLoading(true)
    imageUpRef.current!.upImage().then((data: UpFileResultInterface) => {
      post(Api.baidu.localTextIdentify, {
        localPath: data.filepath
      }).then((data: any) => {
        setWordsResult(data.words_result)
        if (data.words_result.length === 0) {
          message.error('没有识别出文字')
        }
      }).catch(() => {
      }).finally(() => {
        setLoading(false)
      })
    }).catch(() => {
      setLoading(false)
    })
  }

  const closeClick = () => {
    setVisible(false)
  }

  const tests = wordsResult.map((text: any, index: number) => {
    return (
      <Paragraph key={ `texts-${index}` } copyable>{ text.words }</Paragraph>
    )
  })

  return (
    <Fragment>
      <Button size={'small'} type="primary" onClick={() => setVisible(true)}>文字识别(本地图片)</Button>
      <ReactNbsp />
      <Modal
        title="文字识别(本地图片)"
        visible={visible}
        onOk={okBtnClick}
        okText={ wordsResult.length > 0 ? '清除' : '识别' }
        confirmLoading={loading}
        width={900}
        destroyOnClose={true}
        onCancel={closeClick}
      >
        {
          wordsResult.length > 0 ?
            tests
            :
            <ImageUp ref={imageUpRef} />
        }

      </Modal>
    </Fragment>
  )
}

export default LocalImageRecognition